package com.wang.servlet;

import com.wang.utils.ConstantsUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author wr
 * @date 2021/10/28 15:32
 */
@WebServlet(name = "upload", urlPatterns = ConstantsUtil.Home.ROOT_PATH + ConstantsUtil.Home.UPLOAD)
@MultipartConfig
public class UploadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part = req.getPart("file");
        String fileName = part.getSubmittedFileName();
        //获取上传的文件名
        if (!"".equals(fileName)) {
            InputStream is = part.getInputStream();
            //动态获取服务器的路径
            String storagePath = req.getServletContext().getRealPath(ConstantsUtil.Storage.STORAGE_ROOT) + req.getSession().getAttribute(ConstantsUtil.Login.USER_KEY);
            FileOutputStream fos = new FileOutputStream(storagePath + "/" + fileName);
            byte[] bty = new byte[1024];
            int length = 0;
            while ((length = is.read(bty)) != -1) {
                fos.write(bty, 0, length);
            }
            req.getRequestDispatcher("/home.jsp").forward(req, resp);
        }else {
            req.getRequestDispatcher("/home.jsp").forward(req, resp);
        }
    }
}
